﻿using System;
using System.Net;
using System.Globalization;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace BotonJXC.Util
{
    public class Utils
    {
        public static string GetHostName()
        {
            return Dns.GetHostName();
        }
        public static DateTime MinTimeStamp
        {
            get { return new DateTime(1970, 1, 1, 8, 0, 1); }
        }
        public static string GetLocalIpV4()
        {
            string hostName = Dns.GetHostName();
            IPHostEntry hEntry = Dns.GetHostEntry(hostName);
            foreach (IPAddress ip in hEntry.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    return ip.ToString();
            }
            return "";
        }
        public static string FormatCurrency(int value)
        {
            NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
            nfi.CurrencyNegativePattern = 1;
            return value.ToString("C0", nfi);
        }
        public static string FormatNumber(object value)
        {
            int num = ToInt(value, 0);
            return num.ToString("N0", CultureInfo.InvariantCulture);
        }
        public static int ToInt(object value, int defValue)
        {
            return ToInt(ToString(value), defValue);
        }
        public static int ToInt(string value, int defValue)
        {
            if (string.IsNullOrEmpty(value))
                return defValue;
            else if (value.Trim().Length == 0)
                return defValue;
            NumberFormatInfo nfi = new NumberFormatInfo();
            nfi.CurrencySymbol = "$";
            nfi.NumberDecimalSeparator = ".";
            nfi.NumberGroupSeparator = ",";
            nfi.NumberGroupSizes = new int[] { 3 };
            try
            {
                int intVal = Int32.Parse(value, NumberStyles.Currency | NumberStyles.AllowCurrencySymbol, nfi);
                return intVal;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return defValue;
            }
        }
        public static float ToFloat(object value, float defValue)
        {
            float val;
            if (float.TryParse(ToString(value), out val))
                return val;
            return defValue;
        }
        public static double ToDouble(object value, double defValue)
        {
            double val;
            if (double.TryParse(ToString(value), out val))
                return val;
            return defValue;
        }
        public static decimal ToDecimal(object value, decimal defValue)
        {
            decimal val;
            if (decimal.TryParse(ToString(value), out val))
                return val;
            return defValue;
        }
        public static string ToString(object value)
        {
            if (value == null)
                return string.Empty;
            return value.ToString();
        }
        public static string ToShortString(object value)
        {
            if (value == null)
                return string.Empty;
            return value.ToString().Trim();
        }
        public static bool IsInteger(object str)
        {
            if (str == null)
                return false;
            int n = 0;
            return int.TryParse(str.ToString(), out n);
        }
        public static bool IsDouble(object str)
        {
            if (str == null)
                return false;
            double n = 0;
            return double.TryParse(str.ToString(), out n);
        }
        /// <summary>
        /// byte[] 轉換為 Image 對象
        /// </summary>
        /// <param name="byteArrayIn"></param>
        /// <param name="index"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static Image BytesToImage(byte[] byteArrayIn, int index, int count)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn, index, count);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
        public static Image BytesToImage(byte[] byteArrayIn)
        {
            return BytesToImage(byteArrayIn, 0, byteArrayIn.Length);
        }
        /// <summary>
        /// Image對象 轉換為 byte[] 數組
        /// </summary>
        /// <param name="image"></param>
        /// <param name="formate"></param>
        /// <returns></returns>
        public static byte[] ImageToBytes(Image image, ImageFormat formate)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, formate);
            return ms.ToArray();
        }
        public static bool InArray(string[] strings, string value)
        {
            return InArray(strings, value, true);
        }
        public static bool InArray(string[] strings, string value, bool ignoreCase)
        {
            if (strings == null)
                return false;
            foreach (string s in strings)
            {
                if (ignoreCase == false && value == s)
                    return true;
                else if (ignoreCase && value.ToLower() == s.ToLower())
                    return true;
            }
            return false;
        }
        public static bool IsBlank(string str)
        {
            if (string.IsNullOrEmpty(str))
                return true;
            else
                return string.IsNullOrEmpty(str.Trim());
        }
        public static bool IsNotBlank(string str)
        {
            if (str == null)
                return false;
            else
                return !string.IsNullOrEmpty(str.Trim());
        }

        public static void SerializeList<T>(string fileName, IList<T> list)
        {
            using (FileStream writer = new FileStream(fileName, FileMode.Create))
            {
                IFormatter formatter = new BinaryFormatter();
                foreach (T stu in list)
                    formatter.Serialize(writer, stu);
            }
        }

        public static IList<T> DeserializeList<T>(string fileName)
        {
            IList<T> list = new List<T>();
            if (File.Exists(fileName))
            {
                try
                {
                    using (FileStream reader = new FileStream(fileName, FileMode.Open))
                    {
                        IFormatter formatter = new BinaryFormatter();
                        while (reader.Position < reader.Length)
                        {
                            list.Add((T)formatter.Deserialize(reader));
                        }

                    }
                }
                catch
                { }
            }
            return list;
        }
    }
}